package com.wh.common.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.MethodDescriptor;
import java.lang.reflect.Method;



public class ServiceLocator implements BeanFactoryAware {
	
	private static BeanFactory beanFactory = null;

	private static ServiceLocator servlocator = null;

	@Override
	public void setBeanFactory(BeanFactory factory) throws BeansException {
		beanFactory = factory;
	}

	public BeanFactory getBeanFactory() {
		return beanFactory;
	}

	public static ServiceLocator getInstance() {
		if (servlocator == null){
			servlocator = (ServiceLocator) beanFactory
					.getBean("serviceLocator");}

		return servlocator;
	}

	/**
	 * 根据提供的bean名称得到相应的服务类
	 * 
	 * @param servName
	 *            bean名称
	 */
	public static Object getService(String servName) {
		try {
			return beanFactory.getBean(servName);
		} catch (BeansException e) {
			 e.printStackTrace();
			return null;
		}
	}

	/**
	 * 根据提供的bean名称得到对应于指定类型的服务类
	 * 
	 * @param servName
	 *            bean名称
	 * @param clazz
	 *            返回的bean类型,若类型不匹配,将抛出异常
	 */
	public static Object getService(String servName, Class<?> clazz) {
		return beanFactory.getBean(servName, clazz);
	}

	public static Object doMethod(Object clz, String method, Object... obj) {
		try {
			Class<?> clazz = clz.getClass();
			BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
			MethodDescriptor[] methords = beanInfo.getMethodDescriptors();
			for (int i = 0; i < methords.length; i++) {
				Method method0 = methords[i].getMethod();
				if (method0.getName().equals(method)) {
					return method0.invoke(clz, obj);
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return null;
	}
}